<template>
	<u-popup :show="show" @close="close" @open="open" mode="bottom" :round="12" :closeable="true"
		@touchmove.stop.prevent="">
		<view class="comment_header">
			<text>{{record?.num}}条评论</text>
		</view>
		<scroll-view class="comment_scroll_view" scroll-y @scrolltolower="activityScrolltolower">
			<template v-if="list?.length > 0">
				<view class="comment_scroll_view_item" v-for="(item,index) in list" :key="item?.id">
					<image :src="item?.avatar" v-if="item?.avatar"></image>
					<image src="http://qianxueapplet.suoeryun.com/avatar.png" v-else>
					</image>
					<view class="comment_scroll_view_item_right">
						<view class="comment_scroll_view_item_right_nickname">{{item?.realname}}</view>
						<view class="comment_scroll_view_item_right_info">{{item?.content}}</view>
						<view class="comment_scroll_view_item_right_img" v-if="item?.imagesUrl">
							<image :src="item?.imagesUrl" @click="handlePreview(item?.imagesUrl)" mode="aspectFill">
							</image>
						</view>
						<view class="comment_scroll_view_item_right_reply">
							<view>
								<text>{{item?.fromToday}}</text>
								<text v-if="item?.location">{{item?.location}}</text>
								<text
									@click="handleReply({...item,parentId:item?.id,replyType:'2',index:index})">回复</text>
							</view>
							<view class="comment_scroll_view_item_right_reply_right" @click="handleLike(item)">
								<image src="http://qianxueapplet.suoeryun.com/likeSelect.png" v-if="item?.isLike">
								</image>
								<image src="http://qianxueapplet.suoeryun.com/like.png" v-else></image>
								<text :style="{color:item?.isLike?'#FF943C':'#666666'}">{{item?.liked}}</text>
							</view>
						</view>
						<template v-if="item?.children && item?.children?.length > 0">
							<view class="comment_scroll_view_item second_level" v-for="child in item?.children">
								<image :src="child?.avatar" v-if="child?.avatar"></image>
								<image src="http://qianxueapplet.suoeryun.com/avatar.png" v-else></image>
								<view class="comment_scroll_view_item_right">
									<view class="comment_scroll_view_item_right_nickname overflow">
										{{child?.realname}}<template v-if="child?.pRealname">
											<image src="http://qianxueapplet.suoeryun.com/commentRight.png">
											</image>{{child?.pRealname}}
										</template>
									</view>
									<view class="comment_scroll_view_item_right_info"><!-- <text v-if="child?.pRealname"
											class="comment_scroll_view_item_right_info_child">@{{child?.pRealname}}</text> -->{{child?.content}}
									</view>
									<view class="comment_scroll_view_item_right_img" v-if="child?.imagesUrl">
										<image :src="child?.imagesUrl" @click="handlePreview(child?.imagesUrl)"
											mode="aspectFill"></image>
									</view>
									<view class="comment_scroll_view_item_right_reply">
										<view>
											<text>{{child?.fromToday}}</text>
											<text v-if="item?.location">{{item?.location}}</text>
											<text
												@click="handleReply({...child,parentId:item?.id,replyType:'3',index:index})">回复</text>
										</view>
										<view class="comment_scroll_view_item_right_reply_right">
											<image src="http://qianxueapplet.suoeryun.com/likeSelect.png"
												v-if="child?.isLike" @click="handleLike(child)">
											</image>
											<image src="http://qianxueapplet.suoeryun.com/like.png" v-else
												@click="handleLike(child)">
											</image>
											<text
												:style="{color:child?.isLike?'#FF943C':'#666666'}">{{child?.liked}}</text>
										</view>
									</view>
								</view>
							</view>
						</template>
						<view class="comment_scroll_view_item_right_seereply"
							v-if="item?.total && item?.children?.length > 0 && item?.total - item?.children?.length > 0"
							@click="handleSeeChildren(item,index)">
							<text>查看{{item?.total - item?.children?.length}}条回复</text> <u-icon name="arrow-down"
								color="#666666"></u-icon>
						</view>
						<view class="comment_scroll_view_item_right_seereply"
							v-if="!item?.children && item?.num !== '0'" @click="handleSeeChildren(item,index)">
							<view class="border"></view>
							<text>查看{{item?.num}}条回复</text> <u-icon name="arrow-down" color="#666666"></u-icon>
						</view>
						<view class="comment_scroll_view_item_right_seereply" v-if="item?.children?.length == item?.num"
							@click="handleSeeChildrenUp(item,index)">
							<view class="border"></view>
							<text>收起</text> <u-icon name="arrow-up" color="#666666"></u-icon>
						</view>
					</view>
				</view>
				<u-loadmore :status="activityStatus" @loadmore="activityScrolltolower"
					v-if="activityStatus !== 'nomore'"></u-loadmore>
			</template>
			<!-- <u-empty v-else text="暂无评论" /> -->
			<u-empty v-else marginTop="20" text="暂无评论" icon="http://qianxueapplet.suoeryun.com/dt.png"></u-empty>
		</scroll-view>
		<view class="comment_bom">
			<view class="comment_bom_row">
				<text @click.stop="handleInput">友善发言...</text>
				<view>
					<image src="http://qianxueapplet.suoeryun.com/photo.png" @click.stop="handleImage"></image>
					<image src="http://qianxueapplet.suoeryun.com/emoji.png" @click.stop="handleExpression"></image>
				</view>
			</view>
		</view>
	</u-popup>
	<!-- 输入弹窗 -->
	<commentInput ref="commentInputRef" @success="handleSuccess"></commentInput>
</template>

<script setup lang="ts">
	import { ref, unref, getCurrentInstance, reactive } from "vue";
	import { showQxOneComments, showQxTwoComments, isLike } from '@/config/index.api';
	import commentInput from '@/components/commentInput.vue';
	import config from '@/common/config';

	const emit = defineEmits(['close']);

	const show = ref(false);
	const list = ref([]);
	const commentInputRef = ref();
	const record = ref()
	const { proxy } = getCurrentInstance();
	const activityPagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	const activityStatus = ref('loadmore');

	async function handleShow(item) {
		show.value = true;
		record.value = item;
		list.value = [];
		loadData();
		uni.$on('refreshCommentList', () => {
			loadData();
			uni.$off('refreshCommentList');
		});
	}

	/**
	 * 加载评论列表
	 */
	async function loadData() {
		if (activityPagination.pageNo === 1) {
			list.value = [];
		}
		const res = await showQxOneComments({ ...unref(record), ...activityPagination });
		activityPagination.total = res?.total;
		list.value?.push(...res?.records);
		if (unref(list)?.length < activityPagination.total) {
			activityStatus.value = 'loadmore';
		} else {
			activityStatus.value = 'nomore';
		}
	}

	/**
	 * 打开
	 */
	function open() {
		console.log('open');
	}

	/**
	 * 关闭
	 */
	function close() {
		activityPagination.pageNo = 1;
		show.value = false;
		emit('close', record.value.num);
	}

	/**
	 * 关闭-外部调用
	 */
	function handleClose() {
		activityPagination.pageNo = 1;
		show.value = false;
	}

	/**
	 * 评论
	 */
	function handleInput() {
		commentInputRef.value.handleShow(unref(record));
	}

	/**
	 * 回复
	 */
	function handleReply(item) {
		commentInputRef.value.handleShow({
			parentId: item?.parentId,
			activityId: item?.activityId,
			answerId: item?.id,
			replyId: item?.userId,
			replyType: item?.replyType,
			type: unref(record)?.type,
			belongId: unref(record)?.belongId,
			index: item?.index,
			pRealname: item?.realname
		});
	}

	/**
	 * 添加图片
	 */
	function handleImage() {
		uni.chooseImage({
			count: 1,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log(tempFilePaths, 'tempFilePaths');
				uni.uploadFile({
					url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						'X-Access-Token': unref(proxy['vuex_token'])
					},
					success: (uploadFileRes) => {
						commentInputRef.value.handleShow({ ...unref(record), imagesUrl: JSON.parse(uploadFileRes.data)?.message });
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '接口异常！'
						})
					}
				});
			}
		});
	}

	/**
	 * 表情
	 */
	function handleExpression() {
		commentInputRef.value.handleShow({ ...unref(record), expression: true });
	}

	/**
	 * 滚动到底部操作
	 */
	function activityScrolltolower() {
		if (unref(list)?.length < activityPagination.total && (unref(list)?.length / activityPagination.pageSize == activityPagination.pageNo)) {
			activityPagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 预览
	 */
	function handlePreview(url) {
		uni.previewImage({
			urls: [url],
		})
	}

	/**
	 * 评论回调
	 */
	function handleSuccess(item, common) {
		console.log(record, item, 'sdf');
		record.value.num++;
		activityPagination.pageNo = 1;
		if (item?.replyType) {
			console.log(item?.replyType, 'item?.replyType');
			// handleSeeChildren(record);
			if (list.value[item?.index].children) {
				list.value[item?.index].children.push(common);
				list.value[item?.index].total = list.value[item?.index].total + 1;
				list.value[item?.index].num = Number(list.value[item?.index].num) + 1;
			} else {
				list.value[item?.index].children = [common];
				list.value[item?.index].total = Number(list.value[item?.index].num) + 1;
				list.value[item?.index].num = Number(list.value[item?.index].num) + 1;
				item.pageNo = 1;
			}
		} else {
			console.log(item?.replyType, 'handleSuccess');
			list.value.push(common);
		}
		// loadData();
	}

	/**
	 * 查看子集
	 */
	async function handleSeeChildren(item, index) {
		console.log(item, 'itme');
		if (item?.children) {
			if (item?.children?.length < 10) {
				item.pageNo = 1;
			} else {
				item.pageNo++;
			}
		} else {
			list.value[index].children = [];
			item.pageNo = 1;
		}
		const res = await showQxTwoComments({ activityId: item?.activityId, parentId: item?.id, pageNo: item?.pageNo, pageSize: 10 });
		if (item?.children?.length < 10) {
			let data = res?.records;
			data?.splice(-item?.children?.length, item?.children?.length)
			list.value[index].children.push(...data);
		} else {
			list.value[index].children.push(...res?.records);
		}
		item.total = res?.total;
	}

	/**
	 * 收取评论
	 */
	function handleSeeChildrenUp(item, index) {
		item.children = null;
	}

	/**
	 * 点赞
	 */
	function handleLike(item) {
		uni.$u.throttle(async () => {
			const res = await isLike({ id: item?.id, isLike: item?.isLike });
			item.isLike = res?.isLike;
			item.liked = res?.liked;
		}, 1000, true);
	}

	defineExpose({
		handleShow,
		handleClose,
	})
</script>

<style lang="scss" scoped>
	.comment_header {
		text-align: center;
		font-size: 34rpx;
		padding: 24rpx 0;
	}

	.comment_scroll_view {
		height: 50vh;

		.comment_scroll_view_item {
			padding: 0 20rpx 24rpx 20rpx;
			display: flex;
			align-items: flex-start;

			&.second_level {
				padding-right: 0;

				&>image {
					width: 56rpx;
					height: 56rpx;
				}
			}

			&>image {
				width: 76rpx;
				height: 76rpx;
				margin-right: 20rpx;
				border-radius: 50%;
			}

			.comment_scroll_view_item_right {
				flex: 1;

				.comment_scroll_view_item_right_nickname {
					// display: flex;
					// align-items: center;
					color: #666666;
					max-width: 65vw;

					image {
						width: 32rpx;
						height: 32rpx;
						vertical-align: middle;
					}
				}

				.comment_scroll_view_item_right_nickname,
				.comment_scroll_view_item_right_info {
					font-size: 30rpx;
					margin-bottom: 16rpx;

					.comment_scroll_view_item_right_info_child {
						color: #FF943C;
						display: inline-block;
						margin-right: 20rpx;
					}
				}

				.comment_scroll_view_item_right_info {
					color: #333333;
				}

				.comment_scroll_view_item_right_img {
					image {
						width: 100rpx;
						height: 100rpx;
						border-radius: 24rpx;
					}
				}

				.comment_scroll_view_item_right_reply {
					font-size: 30rpx;
					color: #999999;
					margin-bottom: 22rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;

					&>view {

						&:first-child {
							flex: 1;
						}

						&>text {
							margin-right: 22rpx;
						}
					}

					image {
						width: 38rpx;
						height: 38rpx;
						margin-right: 10rpx;
						vertical-align: text-bottom;
					}

					.comment_scroll_view_item_right_reply_right {
						color: #FF943C;
					}
				}

				.comment_scroll_view_item_right_seereply {
					font-size: 30rpx;
					color: #666666;
					display: flex;
					align-items: center;

					.border {
						width: 40rpx;
						margin-right: 10rpx;
						border-top: 2rpx dashed #666666;
					}

					text {
						display: inline-block;
						margin-right: 10rpx;
					}
				}
			}
		}

	}

	.comment_bom {
		height: 88rpx;
		padding: 18rpx 26rpx;
		background-color: #fff;

		.comment_bom_row {
			background-color: #F0F0F0;
			border-radius: 50rpx;
			color: #9E9E9E;
			height: 64rpx;
			padding: 14rpx 22rpx;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			text {
				flex: 1;
			}

			image {
				width: 48rpx;
				height: 48rpx;
				margin-right: 15px;
				vertical-align: text-top;

				&:last-child {
					margin-right: 12rpx;
				}
			}
		}
	}
</style>